// pages/order/list.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderList: [],
    tabs: ['全部', '待付款', '已完成', '已取消'],
    currentTab: 0,
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.tab) {
      const tabIndex = parseInt(options.tab);
      if (tabIndex >= 0 && tabIndex < this.data.tabs.length) {
        this.setData({
          currentTab: tabIndex
        });
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      pageNum: 1,
      hasMore: true,
      orderList: []
    });
    this.loadOrderList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      hasMore: true,
      orderList: []
    });
    this.loadOrderList(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreOrders();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的订单',
      path: '/pages/order/list'
    };
  },

  /**
   * 切换标签
   */
  switchTab(e) {
    const tabIndex = e.currentTarget.dataset.index;
    if (tabIndex !== this.data.currentTab) {
      this.setData({
        currentTab: tabIndex,
        pageNum: 1,
        hasMore: true,
        orderList: []
      });
      this.loadOrderList();
    }
  },

  /**
   * 加载订单列表
   */
  loadOrderList(callback) {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    // 模拟API请求
    setTimeout(() => {
      // 根据当前标签获取不同状态的订单
      let status = '';
      switch (this.data.currentTab) {
        case 1:
          status = 'unpaid';
          break;
        case 2:
          status = 'completed';
          break;
        case 3:
          status = 'cancelled';
          break;
        default:
          status = '';
      }
      
      // 模拟订单数据
      const mockOrders = this.getMockOrders(status, this.data.pageNum, this.data.pageSize);
      
      this.setData({
        orderList: mockOrders,
        loading: false,
        hasMore: mockOrders.length >= this.data.pageSize
      });
      
      if (typeof callback === 'function') {
        callback();
      }
    }, 800);
  },

  /**
   * 加载更多订单
   */
  loadMoreOrders() {
    if (this.data.loading || !this.data.hasMore) return;
    
    this.setData({
      pageNum: this.data.pageNum + 1,
      loading: true
    });
    
    // 模拟API请求
    setTimeout(() => {
      // 根据当前标签获取不同状态的订单
      let status = '';
      switch (this.data.currentTab) {
        case 1:
          status = 'unpaid';
          break;
        case 2:
          status = 'completed';
          break;
        case 3:
          status = 'cancelled';
          break;
        default:
          status = '';
      }
      
      // 模拟订单数据
      const mockOrders = this.getMockOrders(status, this.data.pageNum, this.data.pageSize);
      
      if (mockOrders.length > 0) {
        this.setData({
          orderList: [...this.data.orderList, ...mockOrders],
          loading: false,
          hasMore: mockOrders.length >= this.data.pageSize
        });
      } else {
        this.setData({
          loading: false,
          hasMore: false
        });
      }
    }, 800);
  },

  /**
   * 获取模拟订单数据
   */
  getMockOrders(status, pageNum, pageSize) {
    const orders = [];
    const startIndex = (pageNum - 1) * pageSize;
    
    // 如果是第3页以后，返回空数组，模拟没有更多数据
    if (pageNum > 2) return [];
    
    for (let i = 0; i < pageSize; i++) {
      const index = startIndex + i;
      // 最多返回15条数据
      if (index >= 15) break;
      
      const orderStatus = this.getRandomStatus(status);
      const courseId = Math.floor(Math.random() * 5) + 1;
      const courseTitles = [
        'Vue.js 3.0 从入门到精通',
        'React 18 实战教程',
        'Flutter 跨平台开发实战',
        'Python 数据分析与可视化',
        'Java 高级开发工程师'
      ];
      
      const order = {
        id: 'ORDER' + (1000 + index),
        orderNo: 'ORDER' + new Date().getFullYear() + this.padZero(new Date().getMonth() + 1) + this.padZero(new Date().getDate()) + (10000 + index),
        courseId: courseId,
        courseTitle: courseTitles[courseId - 1],
        coverUrl: `/assets/images/course/course${courseId}.png`,
        price: Math.floor(Math.random() * 300) + 100,
        createTime: this.getRandomDate(),
        status: orderStatus,
        statusText: this.getStatusText(orderStatus)
      };
      
      orders.push(order);
    }
    
    return orders;
  },

  /**
   * 获取随机状态
   */
  getRandomStatus(status) {
    if (status) return status;
    
    const statuses = ['unpaid', 'completed', 'cancelled'];
    const randomIndex = Math.floor(Math.random() * statuses.length);
    return statuses[randomIndex];
  },

  /**
   * 获取状态文本
   */
  getStatusText(status) {
    switch (status) {
      case 'unpaid':
        return '待付款';
      case 'completed':
        return '已完成';
      case 'cancelled':
        return '已取消';
      default:
        return '未知状态';
    }
  },

  /**
   * 获取随机日期
   */
  getRandomDate() {
    const now = new Date();
    const days = Math.floor(Math.random() * 30);
    const date = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
    
    return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())} ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}:${this.padZero(date.getSeconds())}`;
  },

  /**
   * 数字补零
   */
  padZero(num) {
    return num < 10 ? '0' + num : num;
  },

  /**
   * 去支付
   */
  goPay(e) {
    const orderId = e.currentTarget.dataset.id;
    const order = this.data.orderList.find(item => item.id === orderId);
    
    if (order) {
      wx.navigateTo({
        url: `/pages/order/confirm?id=${order.courseId}&orderNo=${order.orderNo}`
      });
    }
  },

  /**
   * 取消订单
   */
  cancelOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          // 模拟取消订单
          const orderList = this.data.orderList.map(item => {
            if (item.id === orderId) {
              return {
                ...item,
                status: 'cancelled',
                statusText: '已取消'
              };
            }
            return item;
          });
          
          this.setData({ orderList });
          
          wx.showToast({
            title: '订单已取消',
            icon: 'success'
          });
        }
      }
    });
  },

  /**
   * 查看订单详情
   */
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    const order = this.data.orderList.find(item => item.id === orderId);
    
    if (order) {
      // 这里可以跳转到订单详情页
      wx.showToast({
        title: '查看订单: ' + order.orderNo,
        icon: 'none'
      });
    }
  },

  /**
   * 去学习
   */
  goToStudy(e) {
    const courseId = e.currentTarget.dataset.courseid;
    
    wx.navigateTo({
      url: `/pages/course/video?id=${courseId}`
    });
  }
})